/*
 * @Author: silence silence9685@163.com
 * @Date: 2023-05-16 11:00:08
 * @LastEditors: silence silence9685@163.com
 * @LastEditTime: 2023-07-31 15:01:15
 * @FilePath: \lenercom_bluetooth_app\lib\pages\Mine\AccountManager\Controller\AccountManagerController.dart
 * @Description: 账号管理控制器
 */
import 'package:ems_neutral_app/pages/Mine/Language/SilLocalizations/SilLocalizations.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';
import 'package:sil_utils_package/sil_utils_package.dart';

import '../../../../../api/ApiUtils.dart';
import '../../../../../api/request/CommonRequest.dart';
import '../../../../../api/request/UserRequest.dart';
import '../../../../../bloc/userbloc/user_bloc.dart';
import '../../../../config/AppInfo.dart';
import '../../../../utils/eventBus/eventBus.dart';
import '../../../../utils/string/StringConstant.dart';

class AccountManagerController extends GetxController {
  /// 用户头像
  final Rx<String?> avatar = (UserBlocTool.userEntity?.avatar).obs;

  /// 用户昵称
  final Rx<String?> nickName = (UserBlocTool.userEntity?.nickName).obs;

  /// 手机号
  final Rx<String?> userPhone = (UserBlocTool.userEntity?.userPhone).obs;

  /// 邮箱
  final Rx<String?> email = (UserBlocTool.userEntity?.email).obs;

  /// 国家
  final Rx<String?> countryName = (UserBlocTool.userEntity?.countryName).obs;
  final Rx<String?> countryId = (UserBlocTool.userEntity?.country).obs;

  /// 当前的区域code
  String get areaCode {
    String? temp = UserBlocTool.userEntity?.areaCode;

    if (SilTools.stringIsEmpty(temp)) {
      return '+86';
    }

    return temp!;
  }

  /// 获取用户信息
  requestUserInfo(
      {required BuildContext context, Function(dynamic)? successHandler}) {
    apiShow(context, api: api_userInfo_info(), success: (result) {
      if (successHandler != null) successHandler(result);

      /// 用户头像
      this.avatar.value = UserBlocTool.userEntity?.avatar;

      /// 用户昵称
      this.nickName.value = UserBlocTool.userEntity?.nickName;

      /// 手机号
      this.userPhone.value = UserBlocTool.userEntity?.userPhone;

      /// 邮箱
      this.email.value = UserBlocTool.userEntity?.email;

      /// 国家
      this.countryName.value = UserBlocTool.userEntity?.countryName;
      this.countryId.value = UserBlocTool.userEntity?.country;
    }, showErrorToast: false);
  }

  /// 请求绑定/修改邮箱
  requestEditEmail(
      {required BuildContext context,
      String? email,
      String? code,
      Function(dynamic)? successHandler}) {
    /// 默认进行绑定
    bool isBanding = true;

    /// 用户当前邮箱
    String? curEmail = UserBlocTool.userEntity?.email;

    /// 判断是否已经绑定手机号：如果有手机号，就就是修改手机号
    if (!SilTools.stringIsEmpty(curEmail) && curEmail!.length > 0) {
      isBanding = false;
    }

    if (SilTools.stringIsEmpty(code)) {
      String? prompt = LangOf(context)?.common?.code_notEmpty;
      if (!SilTools.stringIsEmpty(prompt)) SilToast.show(prompt!);
      return;
    }

    if (SilTools.stringIsEmpty(email)) {
      String? prompt = LangOf(context)?.common?.email_notEmpty;
      if (!SilTools.stringIsEmpty(prompt)) SilToast.show(prompt!);
      return;
    }

    if (email!.email() == false) {
      String? prompt = LangOf(context)?.common?.email_correctFormat;
      if (!SilTools.stringIsEmpty(prompt)) SilToast.show(prompt!);
      return;
    }

    /// 如果是修改邮箱，需要验证两个邮箱是否一致
    if (isBanding == false) {
      if (email == UserBlocTool.userEntity?.email) {
        String? prompt = LangOf(context)?.common?.email_not_match;
        if (!SilTools.stringIsEmpty(prompt)) SilToast.show(prompt!);
        return;
      }
    }

    String? alertTitle = isBanding
        ? LangOf(context)?.common?.bind_email
        : LangOf(context)?.user?.edit_email;
    String? alertContent =
        '${LangOf(context)?.common?.email_desc1}${email}${LangOf(context)?.common?.email_desc2}${LangOf(context)?.common?.dis_desc3}';
    String? alertCancelTitle = LangOf(context)?.common?.cancel;
    String? alertConfirmTitle = LangOf(context)?.common?.confirm;

    /// 弹窗确认
    SilAlertDialog.showAlertDialog(
        context,
        SilAlertDialogData(
            title: alertTitle,
            content: alertContent,
            cancelButtonTitle: alertCancelTitle,
            confrimButtonTitle: alertConfirmTitle), confrimFunc: () {
      apiShow(context,
          api: api_user_change_email(
            email: email,
            code: code!,
          ), success: (result) {
        /// 提示修改成功
        String? success = isBanding
            ? LangOf(context)?.common?.binding_success
            : LangOf(context)?.common?.edit_success;
        if (!SilTools.stringIsEmpty(success)) SilToast.show(success!);
        UserBlocTool.userEntity?.email = email;
        this.email.value = email;
        if (successHandler != null) successHandler(result);
      }, showErrorToast: true);
    });
  }

  /// 请求绑定/修改用户手机号
  requestEditPhone(
      {required BuildContext context,
      String? phone,
      String? code,
      String? areaCode,
      Function(dynamic)? successHandler}) {
    /// 默认进行绑定
    bool isBanding = true;

    /// 用户当前手机号
    String? curPhone = UserBlocTool.userEntity?.userPhone;

    /// 判断是否已经绑定手机号：如果有手机号，就是修改手机号
    if (!SilTools.stringIsEmpty(curPhone) && curPhone!.length > 0) {
      isBanding = false;
    }

    if (SilTools.stringIsEmpty(code)) {
      String? prompt = LangOf(context)?.common?.code_notEmpty;
      if (!SilTools.stringIsEmpty(prompt)) SilToast.show(prompt!);
      return;
    }

    if (SilTools.stringIsEmpty(phone)) {
      String? prompt = LangOf(context)?.common?.phone_notEmpty;
      if (!SilTools.stringIsEmpty(prompt)) SilToast.show(prompt!);
      return;
    }

    if (phone!.phoneNumber() == false) {
      String? prompt = LangOf(context)?.common?.phone_correctFormat;
      if (!SilTools.stringIsEmpty(prompt)) SilToast.show(prompt!);
      return;
    }

    /// 如果是修改手机号，需要验证两个手机号是否一致
    if (isBanding == false) {
      if (phone == UserBlocTool.userEntity?.userPhone) {
        String? prompt = LangOf(context)?.common?.phone_not_match;
        if (!SilTools.stringIsEmpty(prompt)) SilToast.show(prompt!);
        return;
      }
    }

    String? alertTitle = isBanding
        ? LangOf(context)?.common?.phone_title
        : LangOf(context)?.user?.edit_phone;
    String? alertContent =
        '${LangOf(context)?.common?.phone_desc1}${phone}${LangOf(context)?.common?.phone_desc2}${LangOf(context)?.common?.dis_desc3}';
    String? alertCancelTitle = LangOf(context)?.common?.cancel;
    String? alertConfirmTitle = LangOf(context)?.common?.confirm;

    /// 弹窗确认
    SilAlertDialog.showAlertDialog(
        context,
        SilAlertDialogData(
            title: alertTitle,
            content: alertContent,
            cancelButtonTitle: alertCancelTitle,
            confrimButtonTitle: alertConfirmTitle), confrimFunc: () {
      apiShow(context,
          api: api_user_change_phone(
              phone: phone,
              code: code!,
              areaCode: areaCode), success: (result) {
        /// 提示修改成功
        String? success = isBanding
            ? LangOf(context)?.common?.binding_success
            : LangOf(context)?.common?.edit_success;
        if (!SilTools.stringIsEmpty(success)) SilToast.show(success!);
        UserBlocTool.userEntity?.userPhone = phone;
        UserBlocTool.userEntity?.areaCode = areaCode;
        this.userPhone.value = phone;
        if (successHandler != null) successHandler(result);
      }, showErrorToast: true);
    });
  }

  /// 请求修改用户昵称
  requestEditNickName(
      {required BuildContext context,
      required String newNickName,
      Function(dynamic)? successHandler}) {
    if (SilTools.stringIsEmpty(newNickName)) {
      String? prompt = LangOf(context)?.common?.nickName_notEmpty;
      if (!SilTools.stringIsEmpty(prompt)) SilToast.show(prompt!);
      return;
    }

    apiShow(context,
        api: api_user_info_modify(
            userId: UserBlocTool.userEntity?.id ?? '',
            nickName: newNickName), success: (result) {
      /// 提示修改成功
      String? success = LangOf(context)?.common?.edit_success;
      if (!SilTools.stringIsEmpty(success)) SilToast.show(success!);
      UserBlocTool.userEntity?.nickName = newNickName;
      this.nickName.value = newNickName;
      if (successHandler != null) successHandler(result);
    }, showErrorToast: true);
  }

  /// 请求搜索国家
  requestSearchCountry({
    required String? searchContext,
  }) {
    return api_search_country(searchContext: searchContext);
  }

  /// 请求修改国家
  requestChangeContry(
      {required BuildContext context,
      required String? countryId,
      required String? countryName,
      Function(dynamic)? successHandler}) {
    if (SilTools.stringIsEmpty(countryName)) {
      String? prompt = LangOf(context)?.common?.country_notEmpty;
      if (!SilTools.stringIsEmpty(prompt)) SilToast.show(prompt!);
      return;
    }

    apiShow(context,
        api: api_user_info_modify(
            userId: UserBlocTool.userEntity?.id,
            countryId: countryId!,
            countryName: countryName!), success: (result) {
      /// 提示修改成功
      String? success = LangOf(context)?.common?.edit_success;
      if (!SilTools.stringIsEmpty(success)) SilToast.show(success!);
      UserBlocTool.userEntity?.countryName = countryName;
      UserBlocTool.userEntity?.country = countryId;
      this.countryName.value = countryName;
      this.countryId.value = countryId;
      if (successHandler != null) successHandler(result);
    }, showErrorToast: true);
  }

  /// 请求设置用户头像
  requestSettingAvatar(
      {required BuildContext context,
      required String filePath,
      Function(dynamic)? successHandler}) {
    api_upload_flie(file: filePath).then((result) {
      String? avatarUrl = result.data;
      if (SilTools.stringIsEmpty(avatarUrl)) {
        /// 提示修改失败
        String? error = LangOf(context)?.common?.dh_error;
        if (!SilTools.stringIsEmpty(error)) SilToast.show(error!);
        return;
      }

      String avatarPath = imgUrl + avatarUrl!;

      apiShow(context,
          api: api_user_info_modify(
            avatarUrl: avatarPath,
            userId: UserBlocTool.userEntity?.id,
          ), success: (result) {
        /// 提示修改成功
        String? success = LangOf(context)?.common?.edit_success;
        if (!SilTools.stringIsEmpty(success)) SilToast.show(success!);
        UserBlocTool.userEntity?.avatar = avatarPath;
        this.avatar.value = avatarPath;
        if (successHandler != null) successHandler(result);
      }, showErrorToast: true, showLoading: true);
    });
  }

  /// 注销账号
  requestDestroyAccount({
    required BuildContext context,
    Function(dynamic)? successHandler,
  }) {
    String? alertTitle = LangOf(context)?.user?.logout;
    String? alertContent = LangOf(context)?.user?.logoutDesc;
    String? alertCancelTitle = LangOf(context)?.common?.cancel;
    String? alertConfirmTitle = LangOf(context)?.common?.confirm;

    /// 弹窗确认
    SilAlertDialog.showAlertDialog(
        context,
        SilAlertDialogData(
            title: alertTitle,
            content: alertContent,
            cancelButtonTitle: alertCancelTitle,
            confrimButtonTitle: alertConfirmTitle), confrimFunc: () {
      apiShow(context,
          api: api_user_destroy_account(
            userId: UserBlocTool.userEntity?.id,
          ), success: (result) {
        // 账号注销成功
        // String? this.en ? res.message : res.data,
        String prompt = result.message ?? result.data;
        SilToast.show(prompt);
        UserBlocTool.loginOut(context);
        UserBlocTool.removeAuth();
        bus.emit(StringConstant.UserLoginOutEvent);
        if (successHandler != null) successHandler(result);
      }, showErrorToast: true);
    });
  }
}
